/*
 *
 * Copyright 2015 gRPC authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

// Package pkg implements a client for Greeter service.
package rpc

import (
	"context"
	"fmt"
	"gfrest/common/rpc/proto/tasks"
	"time"

	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/os/glog"
	"google.golang.org/grpc"
)

// """
// response status
// 0   请求处理成功
// 100 重复请求
// 101 错误的请求方法
// 102 param error - appid
// 103 param error - timestamp
// 104 param error–reqinfo
// 105 param error - v
// 106 param error - nonce
// 107 param error – sign
// 108 param error - echostr
// 201 访问量超过限制
// 500 未知处理状态
// 501 服务处理错误

// urltype   url分类
// 1 灰
// 2 黑（具体的恶意类型参考恶意类型定义Eviltype字段)
// 3 非腾讯白名单
// 4 腾讯白名单

// evilclass  恶意类型（大类）
// 1 社工欺诈
// 2 信息诈骗
// 3 虚假销售
// 4 恶意文件
// 5 博彩网站
// 6 色情网站
// 7 风险网站
// 8 非法内容
// """

var (
	address = g.Config().GetString("rpcAddr", "127.0.0.1:50051")
)

var c tasks.TasksServiceClient
var conn grpc.ClientConn

func init() {
	g.Log().Info("address", address)
	conn, err := grpc.Dial(address, grpc.WithInsecure())
	if err != nil {
		glog.Errorf("did not connect: %v", err)
	}
	// defer conn.Close()
	c = tasks.NewTasksServiceClient(conn)

}

// Cleanup Cleanup
func Cleanup() {
	conn.Close()
}

// DoTask DoTask
func DoTask(Domain string) *tasks.TaskResponse {
	defer func() {
		if r := recover(); r != nil {
			fmt.Println("recover:", r)
		}
	}()
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	taskRes := &tasks.TaskRequest{IP: Domain}
	ret, err := c.DoTask(ctx, taskRes)
	if err != nil {
		glog.Errorf("could not greet: %v", err)
		return nil
	}
	g.Log().Printf("go client Greeting: %v", ret)
	return ret
}
